<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="../../plugins/element-ui/index.css" />
  <link rel="stylesheet" href="../../styles/common.css" />
  <link rel="stylesheet" href="../../styles/page.css" />
</head>
<body>
  <div class="addBrand-container" id="member-add-app">
    <div class="container">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        :inline="false"
        label-width="180px"
        class="demo-ruleForm"
      >
        <el-form-item label="图书名称:" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入图书名称" maxlength="20"/>
        </el-form-item>

        <el-form-item label="图书作者:" prop="author">
          <el-input v-model="ruleForm.author" placeholder="请输入图书作者" maxlength="20"/>
        </el-form-item>

        <el-form-item label="图书价格:" prop="price">
          <el-input v-model="ruleForm.price" placeholder="请输入图书价格" maxlength="20"/>
          </el-form-item>

        <!--<el-form-item label="图书类型:" prop="type_id">
            <el-input v-model="ruleForm.type_id" placeholder="请输入图书类型" maxlength="50"/>
          </el-form-item>-->
        <el-form-item label="图书类型:" prop="typeId">
        <el-select v-model="ruleForm.typeId" placeholder="请选择图书类型">
          <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.type"
                  :value="item.id"
                  :disabled="item.disabled">
          </el-option>
        </el-select>
        </el-form-item>
        <el-form-item
                label="图片:"
                prop="region"
                class="uploadImg"
        >
          <el-upload
                  class="avatar-uploader"
                  action="/common/upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :on-change="onChange"
                  ref="upload"
          >
            <img
                    v-if="imageUrl"
                    :src="imageUrl"
                    class="avatar"
            ></img>
            <i
                    v-else
                    class="el-icon-plus avatar-uploader-icon"
            ></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="图书详情:" prop="description">
            <el-input v-model="ruleForm.description" placeholder="请输入图书详情" maxlength="50"/>
        </el-form-item>


        <div class="subBox address">
          <el-form-item>
            <el-button  @click="goBack()">
              取消
            </el-button>
            <el-button
              type="primary"
              @click="submitBookForm('ruleForm', false)"
            >
              保存
            </el-button>
            <el-button
              v-if="actionType == 'add'"
              type="primary"
              class="continue"
              @click="submitBookForm('ruleForm', true)"
            >
              保存并继续添加
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
    <!-- 开发环境版本，包含了有帮助的命令行警告 -->
    <script src="../../plugins/vue/vue.js"></script>
    <!-- 引入组件库 -->
    <script src="../../plugins/element-ui/index.js"></script>
    <!-- 引入axios -->
    <script src="../../plugins/axios/axios.min.js"></script>
    <script src="../../js/request.js"></script>
    <script src="../../api/book.js"></script>
    <script src="../../js/validate.js"></script>
    <script src="../../js/index.js"></script>
    <script>
      new Vue({
        el: '#member-add-app',
        data() {
          return {
            id: '',
            type:'',
            actionType : '',
            ruleForm : {
                name: '',
                author: '',
                price: '',
                typeId: '',
                description: '',
                type: '',
                image:''
            },
            imageUrl: '',
            options: [],
            value: ''
          }
        },
        computed: {
          rules () {
            return {
              //账号
              username: [
                {
                  required: true, 'validator': checkUserName, trigger: 'blur'
                }
              ],
              //姓名
              name: [{ required: true, 'validator': checkName, 'trigger': 'blur' }],
              'phone': [{ 'required': true, 'validator': checkPhone, 'trigger': 'blur' }],
              'idNumber': [{ 'required': true, 'validator': validID, 'trigger': 'blur' }]
            }
          }
        },
        created() {
          this.getBookType();
          this.id = requestUrlParam('id')
          this.type = requestUrlParam('type')
          console.log(this.type)
          this.actionType = this.id ? 'edit' : 'add'
          console.log('actionType',this.actionType)
          if (this.id) {
            this.init()
          }
        },
        mounted() {

        },
        methods: {
          async init() {
            queryBookById(this.id).then(res => {
              console.log(res)
              if (String(res.code) === '1') {
                console.log(res.data)
                this.ruleForm = res.data
                this.imageUrl = `/common/download?name=${res.data.image}`
              } else {
                this.$message.error(res.msg || '操作失败')
              }
            })
          },
          handleAvatarSuccess (response, file, fileList) {
            // 拼接down接口预览
            if(response.code === 0 && response.msg === '未登录'){
              window.top.location.href = '/backend/page/login/login.html'
            }else{
              this.imageUrl = `/common/download?name=${response.data}`
              this.ruleForm.image = response.data
            }
          },
          onChange (file) {
            if(file){
              const suffix = file.name.split('.')[1]
              const size = file.size / 1024 / 1024 < 2
              if(['png','jpeg','jpg'].indexOf(suffix) < 0){
                this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
                this.$refs.upload.clearFiles()
                return false
              }
              if(!size){
                this.$message.error('上传文件大小不能超过 2MB!')
                return false
              }
              return file
            }
          },
          getBookType() {
            getType().then(res => {
              console.log(res)
              if (String(res.code) === '1'){
                console.log(res.data)
                this.options = res.data
              }
            })
          },
          submitBookForm (formName, st) {

                if (this.type == 'add') {
                  const params = {
                    ...this.ruleForm,
                  }
                  if(!this.imageUrl){
                    this.$message.error('请上传菜品图片')
                    return
                  }
                  console.log(params)
                  addBook(params).then(res => {
                    if (res.code === 1) {
                      this.$message.success('图书添加成功！')
                      if (!st) {
                        this.goBack()
                      } else {
                        this.imageUrl = ''
                        this.ruleForm = {
                          name: '',
                          author: '',
                          price: '',
                          type: '',
                          typeId: '',
                          image:'',
                          description: '',
                        }
                      }
                    } else {
                      this.$message.error(res.msg || '操作失败')
                    }
                  }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                  })
                } else {
                  const params = {
                    ...this.ruleForm,
                    sex: this.ruleForm.sex === '女' ? '0' : '1'
                  }
                  editBook(params).then(res => {
                    if (res.code === 1) {
                      this.$message.success('图书信息修改成功！')
                      this.goBack()
                    } else {
                      this.$message.error(res.msg || '操作失败')
                    }
                  }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                  })
                }


          },
          goBack(){
            window.parent.menuHandle({
              id: '2',
              url: '/backend/page/info/list.html',
              name: '图书管理'
            },false)
          }
        }
      })
    </script>
</body>
</html>